<template>
  <div class="clipboard-tab">
    <n-spin :show="loading">
      <!-- 创建模式 -->
      <template v-if="mode === 'create'">
        <n-form ref="formRef" :model="createForm" label-placement="top">
          <n-form-item label="内容" path="content" :rule="{ required: true, message: '请输入内容' }">
            <n-input
              v-model:value="createForm.content"
              type="textarea"
              placeholder="输入要分享的文本内容..."
              :rows="15"
              show-count
            />
          </n-form-item>

          <n-grid :cols="12" :x-gap="16" :y-gap="16">
            <n-gi :span="isMobile ? 12 : 6">
              <n-form-item label="访问密码" path="password">
                <n-input
                  v-model:value="createForm.password"
                  type="password"
                  placeholder="留空表示无密码保护"
                  show-password-on="click"
                />
              </n-form-item>
            </n-gi>
            <n-gi :span="isMobile ? 12 : 6">
              <n-form-item label="访问次数限制" path="maxAccessCount">
                <n-input-number
                  v-model:value="createForm.maxAccessCount"
                  placeholder="不限制"
                  :min="1"
                  :max="10000"
                  style="width: 100%"
                />
              </n-form-item>
            </n-gi>
          </n-grid>

          <n-grid :cols="12" :x-gap="16" :y-gap="16">
            <n-gi :span="isMobile ? 12 : 6">
              <n-form-item label="过期时间" path="expireTime">
                <n-date-picker
                  v-model:value="createForm.expireTime"
                  type="datetime"
                  placeholder="默认24小时后过期"
                  :is-date-disabled="dateDisabled"
                  style="width: 100%"
                />
              </n-form-item>
            </n-gi>
            <n-gi :span="isMobile ? 12 : 6">
              <n-form-item label="编辑权限" path="isEditable">
                <n-switch v-model:value="createForm.isEditable">
                  <template #checked>允许编辑</template>
                  <template #unchecked>只读</template>
                </n-switch>
              </n-form-item>
            </n-gi>
          </n-grid>

          <n-button
            type="primary"
            block
            size="large"
            @click="handleCreate"
            :disabled="!createForm.content"
          >
            创建剪贴板
          </n-button>
        </n-form>
      </template>

      <!-- 管理模式 - 左右两栏布局 -->
      <template v-else-if="mode === 'manage' && clipboardData">
        <n-grid :cols="12" :x-gap="24">
          <!-- 左侧内容区 -->
          <n-gi :span="isMobile ? 12 : 8">
            <div class="content-area">
              <n-form-item label="剪贴板内容">
                <n-input
                  v-model:value="accessContent"
                  type="textarea"
                  :rows="20"
                  :readonly="!canEdit"
                  show-count
                />
              </n-form-item>

              <n-space>
                <n-button @click="handleCopyContent">复制内容</n-button>
                <n-button
                  v-if="canEdit && contentChanged"
                  type="primary"
                  @click="handleUpdateContent"
                >
                  保存修改
                </n-button>
                <n-button @click="handleRefresh">刷新</n-button>
              </n-space>
            </div>
          </n-gi>

          <!-- 右侧设置区 -->
          <n-gi :span="isMobile ? 12 : 4">
            <div class="settings-area">
              <!-- 分享链接 -->
              <n-card title="分享链接" size="small" type="primary" style="margin-bottom: 16px;">
                <!-- 二维码展示 -->
                <div class="qrcode-section">
                  <n-spin :show="qrcodeLoading">
                    <n-image
                      v-if="qrcodeData"
                      :src="qrcodeData"
                      :alt="`分享ID: ${clipboardData.shareId}`"
                      :preview-disabled="false"
                      object-fit="contain"
                      style="width: 100%; max-width: 180px; margin: 0 auto 16px; display: block;"
                    />
                    <n-empty
                      v-else-if="!qrcodeLoading && !qrcodeData"
                      description="二维码生成失败"
                      size="small"
                      style="margin-bottom: 16px;"
                    />
                  </n-spin>
                </div>

                <n-input :value="shareUrl" readonly />
                <n-button size="small" block type="primary" @click="() => copyText(shareUrl)" style="margin-top: 8px;">
                  复制分享链接
                </n-button>
              </n-card>

              <!-- 基础信息 -->
              <n-card title="基础信息" size="small" style="margin-bottom: 16px;">
                <n-descriptions :column="1" size="small">
                  <n-descriptions-item label="分享ID">
                    <n-space>
                      <n-text strong>{{ clipboardData.shareId }}</n-text>
                      <n-button size="tiny" @click="() => copyText(clipboardData!.shareId)">复制</n-button>
                    </n-space>
                  </n-descriptions-item>
                  <n-descriptions-item label="剩余时间">
                    <n-text>{{ remainingTimeText }}</n-text>
                  </n-descriptions-item>
                  <n-descriptions-item label="访问次数">
                    <n-text>
                      {{ clipboardData.accessCount }}
                      <template v-if="clipboardData.maxAccessCount">
                        / {{ clipboardData.maxAccessCount }}
                      </template>
                    </n-text>
                  </n-descriptions-item>
                </n-descriptions>
              </n-card>

              <!-- 编辑权限设置 -->
              <n-card title="编辑权限" size="small" style="margin-bottom: 16px;">
                <n-space vertical>
                  <n-space>
                    <n-icon :component="clipboardData.isEditable ? CreateOutline : BookOutline" />
                    <n-text>
                      {{ clipboardData.isEditable ? '访客可编辑' : '访客只读' }}
                    </n-text>
                  </n-space>
                  <n-text v-if="isAdmin" depth="3" style="font-size: 12px;">
                    管理员始终可编辑
                  </n-text>
                  <n-button
                    v-if="isAdmin"
                    size="small"
                    block
                    @click="handleToggleEditable"
                  >
                    设为{{ clipboardData.isEditable ? '访客只读' : '访客可编辑' }}
                  </n-button>
                </n-space>
              </n-card>

              <!-- 密码管理（管理员可见） -->
              <n-card v-if="isAdmin" title="密码管理" size="small" style="margin-bottom: 16px;">
                <n-space vertical>
                  <!-- 管理员密码 -->
                  <n-descriptions :column="1" size="small">
                    <n-descriptions-item label="管理员密码">
                      <n-space>
                        <n-text type="error">{{ maskPassword(adminPassword) }}</n-text>
                        <n-button size="tiny" @click="() => copyText(adminPassword)">复制</n-button>
                      </n-space>
                    </n-descriptions-item>
                  </n-descriptions>
                  <n-space>
                    <n-button size="small" @click="showAdminPasswordModal = true">
                      修改管理员密码
                    </n-button>
                    <n-button size="small" @click="handleGenerateAdminPassword">
                      生成随机管理员密码
                    </n-button>
                  </n-space>

                  <!-- 访问密码 -->
                  <n-descriptions :column="1" size="small" style="margin-top: 16px;">
                    <n-descriptions-item label="访问密码">
                      <n-space v-if="clipboardData.accessPassword">
                        <n-text>{{ clipboardData.accessPassword }}</n-text>
                        <n-button size="tiny" @click="() => copyText(clipboardData.accessPassword!)">复制</n-button>
                      </n-space>
                      <n-text v-else type="info">无密码保护</n-text>
                    </n-descriptions-item>
                  </n-descriptions>
                  <n-space>
                    <n-button size="small" @click="showPasswordModal = true">
                      修改访问密码
                    </n-button>
                    <n-button size="small" @click="handleGeneratePassword">
                      生成随机访问密码
                    </n-button>
                  </n-space>
                </n-space>
              </n-card>

              <!-- 时间设置（管理员可见） -->
              <n-card v-if="isAdmin" title="时间设置" size="small" style="margin-bottom: 16px;">
                <n-space vertical>
                  <n-text depth="3">当前过期时间：{{ formatExpireTime(clipboardData.expireTime) }}</n-text>
                  <n-button size="small" block @click="showExpireModal = true">
                    设置过期时间
                  </n-button>
                </n-space>
              </n-card>

              <!-- 危险操作（管理员可见） -->
              <n-card v-if="isAdmin" title="危险操作" size="small">
                <n-button size="small" block type="error" @click="handleDeleteClipboard">
                  删除剪贴板
                </n-button>
              </n-card>
            </div>
          </n-gi>
        </n-grid>
      </template>
    </n-spin>

    <!-- 弹窗 -->
    <n-modal
      v-model:show="showExpireModal"
      title="设置过期时间"
      preset="dialog"
      positive-text="确定"
      negative-text="取消"
      @positive-click="handleSetExpireTime"
    >
      <n-form-item label="新的过期时间">
        <n-date-picker
          v-model:value="newExpireTime"
          type="datetime"
          placeholder="选择新的过期时间"
          :is-date-disabled="dateDisabled"
          style="width: 100%"
        />
      </n-form-item>
    </n-modal>

    <n-modal
      v-model:show="showPasswordModal"
      title="修改访问密码"
      preset="dialog"
      positive-text="确定"
      negative-text="取消"
      @positive-click="handleChangeAccessPassword"
    >
      <n-form-item label="新访问密码">
        <n-input
          v-model:value="newAccessPassword"
          type="password"
          placeholder="留空表示移除访问密码"
          show-password-on="click"
        />
      </n-form-item>
    </n-modal>

    <n-modal
      v-model:show="showAdminPasswordModal"
      title="修改管理员密码"
      preset="dialog"
      positive-text="确定"
      negative-text="取消"
      @positive-click="handleChangeAdminPassword"
    >
      <n-form-item label="新管理员密码">
        <n-input
          v-model:value="newAdminPassword"
          type="password"
          placeholder="输入新的管理员密码"
          show-password-on="click"
        />
      </n-form-item>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, h, watch } from 'vue'
import { useMessage } from 'naive-ui'
import axios from '@/utils/axios'
import {
  TimeOutline,
  EyeOutline,
  CreateOutline,
  BookOutline,
  SettingsOutline,
  KeyOutline,
  RefreshOutline,
  CalendarOutline,
  TrashOutline
} from '@vicons/ionicons5'
import { useBreakpoint } from '@/utils/responsive-helper'
import {
  createClipboard,
  getClipboard,
  updateClipboard,
  setExpireTime,
  changeAccessPassword,
  generateAccessPassword,
  changeAdminPassword,
  generateAdminPassword,
  deleteClipboard,
  type CreateClipboardParams,
  type UpdateClipboardParams,
  type ClipboardData
} from '@/api/utility/clipboard'
import { clipboardStorage } from '../utils/clipboardStorage'
import { quickGenerateQRCode } from '@/utils/qrcode-generator'

export interface ClipboardTabProps {
  tabId: string
  shareId?: string
  isCreate?: boolean
}

const props = defineProps<ClipboardTabProps>()
const emit = defineEmits<{
  'update:title': [title: string]
  'close': []
}>()

const message = useMessage()
const { isMobile } = useBreakpoint()

// 模式：create（创建）或 manage（管理）
const mode = ref<'create' | 'manage'>(props.isCreate ? 'create' : 'manage')
const loading = ref(false)

// 创建模式数据
const createForm = reactive<CreateClipboardParams>({
  content: '',
  password: undefined,
  expireTime: undefined,
  isEditable: false,
  maxAccessCount: undefined
})

// 管理模式数据
const clipboardData = ref<ClipboardData | null>(null)
const accessContent = ref('')
const contentChanged = computed(() => {
  return clipboardData.value && accessContent.value !== clipboardData.value.content
})

// 权限和密码
const isAdmin = ref(false)
const adminPassword = ref('')
const accessPassword = ref('')

// 弹窗状态
const showExpireModal = ref(false)
const newExpireTime = ref<number | null>(null)
const showPasswordModal = ref(false)
const newAccessPassword = ref('')
const showAdminPasswordModal = ref(false)
const newAdminPassword = ref('')

// 是否可以编辑（简化逻辑：管理员始终可编辑，普通用户看设置）
const canEdit = computed(() => {
  if (!clipboardData.value) return false
  // 管理员始终可以编辑
  if (isAdmin.value) return true
  // 普通用户根据设置决定：如果允许编辑且有访问密码，就可以编辑
  return clipboardData.value.isEditable
})

// 剩余时间显示
const remainingTimeText = computed(() => {
  if (!clipboardData.value) return '--'
  const hours = clipboardData.value.remainingHours
  if (hours < 1) {
    return '即将过期'
  } else if (hours < 24) {
    return `${hours}小时`
  } else {
    const days = Math.floor(hours / 24)
    const remainingHours = hours % 24
    if (remainingHours === 0) {
      return `${days}天`
    }
    return `${days}天${remainingHours}小时`
  }
})

// 分享链接
const shareUrl = computed(() => {
  if (!clipboardData.value) return ''
  const baseUrl = window.location.origin
  const queryParams = new URLSearchParams()
  queryParams.set('shareId', clipboardData.value.shareId)
  return `${baseUrl}/utilityTool/clipboard?${queryParams.toString()}`
})

// 二维码相关
const qrcodeData = ref<string | null>(null)
const qrcodeLoading = ref(false)

// 生成二维码
const generateQRCodeForUrl = async (url: string) => {
  if (!url) return

  qrcodeLoading.value = true
  try {
    const result = await quickGenerateQRCode(url, 200)
    qrcodeData.value = result
  } catch (error) {
    console.error('生成二维码失败:', error)
    qrcodeData.value = null
  } finally {
    qrcodeLoading.value = false
  }
}

// 监听 shareUrl 变化，自动生成二维码
watch(shareUrl, (newUrl) => {
  if (newUrl) {
    generateQRCodeForUrl(newUrl)
  }
}, { immediate: true })

// 日期禁用规则
const dateDisabled = (ts: number) => {
  return ts < Date.now()
}

// 格式化日期时间
const formatDateTime = (timestamp: number): string => {
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 格式化过期时间显示
const formatExpireTime = (expireTime: string): string => {
  const date = new Date(expireTime)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 密码掩码
const maskPassword = (password: string): string => {
  if (password.length <= 4) return '****'
  return password.substring(0, 2) + '****' + password.substring(password.length - 2)
}

// 创建剪贴板
const handleCreate = async () => {
  if (!createForm.content.trim()) {
    message.warning('请输入内容')
    return
  }

  loading.value = true
  try {
    const params: CreateClipboardParams = {
      content: createForm.content,
      isEditable: createForm.isEditable
    }

    if (createForm.password) {
      params.password = createForm.password
    }

    if (createForm.expireTime) {
      params.expireTime = formatDateTime(createForm.expireTime)
    }

    if (createForm.maxAccessCount) {
      params.maxAccessCount = createForm.maxAccessCount
    }

    const result = await createClipboard(params)

    // 保存到IndexedDB
    await clipboardStorage.saveClipboard({
      shareId: result.shareId,
      adminPassword: result.adminPassword,
      accessPassword: createForm.password,
      title: result.shareId,
      createdAt: Date.now(),
      lastAccessAt: Date.now(),
      isAdmin: true
    })

    message.success('创建成功！')

    // 创建成功后直接打开新标签页
    emit('update:title', `新建: ${result.shareId}`)

    // 触发父组件打开新tab
    setTimeout(() => {
      const event = new CustomEvent('clipboard-created', {
        detail: {
          shareId: result.shareId,
          adminPassword: result.adminPassword,
          accessPassword: createForm.password
        }
      })
      window.dispatchEvent(event)
    }, 100)
  } catch (error: any) {
    message.error(error.message || '创建失败')
  } finally {
    loading.value = false
  }
}

// 加载剪贴板数据
const loadClipboard = async () => {
  if (!props.shareId) return

  loading.value = true
  try {
    // 先从IndexedDB获取最新密码
    await refreshPasswordFromDB()

    const currentPassword = isAdmin.value ? adminPassword.value : accessPassword.value
    const params: any = {
      shareId: props.shareId
    }

    // 只有在有密码的情况下才传递密码参数
    if (currentPassword) {
      params.password = currentPassword
    }

    const data = await getClipboard(params)
    clipboardData.value = data
    accessContent.value = data.content

    // 使用后端返回的isAdmin字段判断管理员身份
    isAdmin.value = data.isAdmin || false

    // 再次从IndexedDB获取密码并更新状态，确保状态一致
    const existingRecord = await clipboardStorage.getClipboardByShareId(props.shareId)
    if (existingRecord) {
      // 只从IndexedDB读取密码，确保使用最新密码
      if (isAdmin.value) {
        adminPassword.value = existingRecord.adminPassword || ''
      } else {
        accessPassword.value = existingRecord.accessPassword || ''
      }

      // 更新最后访问时间
      await clipboardStorage.updateClipboard(existingRecord.id, {
        lastAccessAt: Date.now(),
        isAdmin: isAdmin.value
      })
    }

    // 更新标签页标题
    emit('update:title', props.shareId)

    if (data.isExpired) {
      message.error('剪贴板已过期')
    }
  } catch (error: any) {
    message.error(error.message || '访问失败')
    // 访问失败时不关闭tab，让用户停留在当前页面
  } finally {
    loading.value = false
  }
}

// 更新剪贴板内容
const handleUpdateContent = async () => {
  if (!clipboardData.value) return

  // 检查是否有编辑权限
  if (!canEdit.value) {
    message.error('您没有编辑权限')
    return
  }

  loading.value = true
  try {
    // 先从IndexedDB获取最新密码
    await refreshPasswordFromDB()

    // 构建更新参数
    const updateParams: UpdateClipboardParams = {
      shareId: clipboardData.value.shareId,
      content: accessContent.value
    }

    // 使用从IndexedDB获取的最新密码
    if (isAdmin.value) {
      updateParams.password = adminPassword.value
    } else {
      updateParams.password = accessPassword.value
    }

    const result = await updateClipboard(updateParams)
    clipboardData.value = result
    accessContent.value = result.content
    message.success('保存成功')
  } catch (error: any) {
    console.error('保存失败:', error)
    message.error(error.message || '保存失败')
  } finally {
    loading.value = false
  }
}

// 切换编辑权限
const handleToggleEditable = async () => {
  if (!clipboardData.value || !isAdmin.value) return

  // 先从IndexedDB获取最新密码
  await refreshPasswordFromDB()

  if (!adminPassword.value) {
    message.error('管理员密码未设置，无法执行管理操作')
    return
  }

  loading.value = true
  try {
    const response = await axios.put('/api/utility/clipboard/set-editable', {
      shareId: clipboardData.value.shareId,
      adminPassword: adminPassword.value,
      isEditable: !clipboardData.value.isEditable
    })

    if (response.code === 200) {
      clipboardData.value = response.data
      message.success(`已设为${response.data.isEditable ? '访客可编辑' : '访客只读'}模式`)
    } else {
      throw new Error(response.message || '设置失败')
    }
  } catch (error: any) {
    message.error(error.message || '设置编辑权限失败')
  } finally {
    loading.value = false
  }
}

// 刷新数据
const handleRefresh = async () => {
  if (!clipboardData.value) return

  loading.value = true
  try {
    // 先从IndexedDB获取最新密码
    await refreshPasswordFromDB()

    const data = await getClipboard({
      shareId: clipboardData.value.shareId,
      password: isAdmin.value ? adminPassword.value : accessPassword.value
    })
    clipboardData.value = data
    accessContent.value = data.content
    message.success('刷新成功')
  } catch (error: any) {
    message.error(error.message || '刷新失败')
  } finally {
    loading.value = false
  }
}

// 设置过期时间
const handleSetExpireTime = async () => {
  if (!clipboardData.value || !newExpireTime.value) {
    message.warning('请选择过期时间')
    return
  }

  // 先从IndexedDB获取最新密码
  await refreshPasswordFromDB()

  if (!adminPassword.value) {
    message.error('管理员密码未设置，无法执行管理操作')
    return
  }

  loading.value = true
  try {
    const result = await setExpireTime({
      shareId: clipboardData.value.shareId,
      adminPassword: adminPassword.value,
      expireTime: formatDateTime(newExpireTime.value)
    })
    clipboardData.value = result
    message.success('设置成功')
  } catch (error: any) {
    message.error(error.message || '设置失败')
  } finally {
    loading.value = false
    showExpireModal.value = false
  }
}

// 修改访问密码
const handleChangeAccessPassword = async () => {
  if (!clipboardData.value) return

  // 先从IndexedDB获取最新密码
  await refreshPasswordFromDB()

  if (!adminPassword.value) {
    message.error('管理员密码未设置，无法执行管理操作')
    return
  }

  loading.value = true
  try {
    await changeAccessPassword({
      shareId: clipboardData.value.shareId,
      adminPassword: adminPassword.value,
      newAccessPassword: newAccessPassword.value || undefined
    })

    accessPassword.value = newAccessPassword.value
    clipboardData.value.hasPassword = !!newAccessPassword.value
    clipboardData.value.accessPassword = newAccessPassword.value

    // 更新IndexedDB
    const record = await clipboardStorage.getClipboardByShareId(clipboardData.value.shareId)
    if (record) {
      await clipboardStorage.updateClipboard(record.id, {
        accessPassword: newAccessPassword.value || undefined
      })
    }

    message.success(newAccessPassword.value ? '访问密码修改成功' : '访问密码已移除')
  } catch (error: any) {
    message.error(error.message || '修改失败')
  } finally {
    loading.value = false
    showPasswordModal.value = false
  }
}

// 生成随机访问密码
const handleGeneratePassword = async () => {
  if (!clipboardData.value) return

  // 先从IndexedDB获取最新密码
  await refreshPasswordFromDB()

  if (!adminPassword.value) {
    message.error('管理员密码未设置，无法执行管理操作')
    return
  }

  loading.value = true
  try {
    const result = await generateAccessPassword({
      shareId: clipboardData.value.shareId,
      adminPassword: adminPassword.value
    })

    accessPassword.value = result.newPassword
    clipboardData.value.hasPassword = true
    clipboardData.value.accessPassword = result.newPassword

    // 更新IndexedDB
    const record = await clipboardStorage.getClipboardByShareId(clipboardData.value.shareId)
    if (record) {
      await clipboardStorage.updateClipboard(record.id, {
        accessPassword: result.newPassword
      })
    }

    window.$dialog.success({
      title: '生成成功',
      content: `新的访问密码：${result.newPassword}`,
      positiveText: '确定'
    })
  } catch (error: any) {
    message.error(error.message || '生成失败')
  } finally {
    loading.value = false
  }
}

// 修改管理员密码
const handleChangeAdminPassword = async () => {
  if (!clipboardData.value) return

  if (!newAdminPassword.value?.trim()) {
    message.warning('请输入新的管理员密码')
    return
  }

  // 先从IndexedDB获取最新密码
  await refreshPasswordFromDB()

  if (!adminPassword.value) {
    message.error('管理员密码未设置，无法执行管理操作')
    return
  }

  loading.value = true
  try {
    await changeAdminPassword({
      shareId: clipboardData.value.shareId,
      oldAdminPassword: adminPassword.value,
      newAdminPassword: newAdminPassword.value
    })

    // 更新本地密码
    adminPassword.value = newAdminPassword.value

    // 更新IndexedDB
    const record = await clipboardStorage.getClipboardByShareId(clipboardData.value.shareId)
    if (record) {
      await clipboardStorage.updateClipboard(record.id, {
        adminPassword: newAdminPassword.value
      })
    }

    message.success('管理员密码修改成功')
  } catch (error: any) {
    message.error(error.message || '修改失败')
  } finally {
    loading.value = false
    showAdminPasswordModal.value = false
    newAdminPassword.value = ''
  }
}

// 生成随机管理员密码
const handleGenerateAdminPassword = async () => {
  if (!clipboardData.value) return

  // 先从IndexedDB获取最新密码
  await refreshPasswordFromDB()

  if (!adminPassword.value) {
    message.error('管理员密码未设置，无法执行管理操作')
    return
  }

  loading.value = true
  try {
    const result = await generateAdminPassword({
      shareId: clipboardData.value.shareId,
      oldAdminPassword: adminPassword.value
    })

    // 更新本地密码
    adminPassword.value = result.newPassword

    // 更新IndexedDB
    const record = await clipboardStorage.getClipboardByShareId(clipboardData.value.shareId)
    if (record) {
      await clipboardStorage.updateClipboard(record.id, {
        adminPassword: result.newPassword
      })
    }

    window.$dialog.success({
      title: '生成成功',
      content: `新的管理员密码：${result.newPassword}`,
      positiveText: '确定'
    })
  } catch (error: any) {
    message.error(error.message || '生成失败')
  } finally {
    loading.value = false
  }
}

// 删除剪贴板
const handleDeleteClipboard = async () => {
  if (!clipboardData.value) return

  // 先从IndexedDB获取最新密码
  await refreshPasswordFromDB()

  if (!adminPassword.value) {
    message.error('管理员密码未设置，无法执行管理操作')
    return
  }

  window.$dialog.warning({
    title: '确认删除',
    content: '删除后无法恢复，确定要删除吗？',
    positiveText: '确定删除',
    negativeText: '取消',
    onPositiveClick: async () => {
      loading.value = true
      try {
        await deleteClipboard({
          shareId: clipboardData.value!.shareId,
          adminPassword: adminPassword.value
        })

        // 从IndexedDB删除
        const record = await clipboardStorage.getClipboardByShareId(clipboardData.value!.shareId)
        if (record) {
          await clipboardStorage.deleteClipboard(record.id)
        }

        message.success('删除成功')
        emit('close')
      } catch (error: any) {
        message.error(error.message || '删除失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 复制文本
const copyText = async (text: string) => {
  try {
    if (navigator.clipboard) {
      await navigator.clipboard.writeText(text)
    } else {
      const textarea = document.createElement('textarea')
      textarea.value = text
      textarea.style.position = 'fixed'
      textarea.style.opacity = '0'
      document.body.appendChild(textarea)
      textarea.select()
      document.execCommand('copy')
      document.body.removeChild(textarea)
    }
    message.success('复制成功')
  } catch (error) {
    message.error('复制失败')
  }
}

// 复制内容
const handleCopyContent = () => {
  copyText(accessContent.value)
}

// 从IndexedDB刷新密码
const refreshPasswordFromDB = async () => {
  if (!props.shareId) return

  const record = await clipboardStorage.getClipboardByShareId(props.shareId)
  if (record) {
    if (record.isAdmin) {
      adminPassword.value = record.adminPassword || ''
      isAdmin.value = true
    } else {
      accessPassword.value = record.accessPassword || ''
      isAdmin.value = false
    }
  }
}

// 初始化
if (!props.isCreate && props.shareId) {
  loadClipboard()
}
</script>

<style scoped lang="less">
.clipboard-tab {
  padding: 16px 0;

  :deep(.n-form-item) {
    margin-bottom: 16px;
  }
}

.content-area {
  min-height: 500px;
}

.settings-area {
  :deep(.n-card) {
    .n-card__content {
      padding: 12px;
    }
  }

  :deep(.n-descriptions) {
    .n-descriptions-item {
      padding: 8px 0;
    }
  }
}

.qrcode-section {
  text-align: center;

  :deep(.n-image) {
    border-radius: 4px;
    padding: 8px;
    background: white;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  }

  @media (prefers-color-scheme: dark) {
    :deep(.n-image) {
      background: rgba(255, 255, 255, 0.05);
    }
  }
}

@media (max-width: 768px) {
  .clipboard-tab {
    :deep(.n-form-item) {
      margin-bottom: 12px;
    }
  }

  .settings-area {
    margin-top: 24px;
  }
}
</style>
